import java.util.Arrays;

public class Main {
    /**
     * 反转链表
     * https://leetcode.cn/problems/reverse-linked-list/
     * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
     */
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ListNode answer = new Main().reverseList(head);
        while (answer != null) {
            System.out.println(answer.val);
            answer = answer.next;
        }
    }

    public ListNode reverseList(ListNode head) {
        ListNode previous = null;
        ListNode current = head;
        ListNode temporary = null;
        while (current != null) {
            temporary = current.next;
            current.next = previous;
            previous = current;
            current = temporary;
        }
        ListNode result = previous;
        return result;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}